package com.csh.subject.domain.handler.subject;

import com.csh.subject.common.enums.IsDeletedFlagEnum;
import com.csh.subject.common.enums.SubjectInfoTypeEnum;
import com.csh.subject.domain.convert.SubjectRadioConvert;
import com.csh.subject.domain.entity.SubjectAnswerBo;
import com.csh.subject.domain.entity.SubjectInfoBo;
import com.csh.subject.domain.entity.SubjectOptionBo;
import com.csh.subject.infra.basic.entity.SubjectRadio;
import com.csh.subject.infra.basic.service.SubjectRadioService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 单选题目的策略类
 */
@Slf4j
@Component
public class RadioTypeHandler implements SubjectTypeHandler {
    @Resource
    private SubjectRadioService subjectRadioService;

    @Override
    public SubjectInfoTypeEnum getHandlerType() {
        return SubjectInfoTypeEnum.RADIO;
    }

    @Override
    public void add(SubjectInfoBo subjectInfoBo) {

        if (subjectInfoBo.getOptionList() != null) {
            //单选题、题目选项的插入
//            List<SubjectRadio> subjectRadioList = new LinkedList<>();
//            subjectInfoBo.getOptionList().forEach(
//                    option -> {
//                        SubjectRadio subjectRadio = SubjectRadioConvert.INSTANCE.convertBoToRadio(option);
//                        subjectRadio.setSubjectId(subjectInfoBo.getId());
//                        subjectRadio.setIsDeleted(IsDeletedFlagEnum.UN_DELETED.getCode());
//                        subjectRadioList.add(subjectRadio);
//                    }
//            );

            //单选题、题目选项的插入
            List<SubjectAnswerBo> subjectAnswerBos = subjectInfoBo.getOptionList();
            List<SubjectRadio> subjectRadioList = subjectAnswerBos.stream().map(
                    option -> {
                        SubjectRadio subjectRadio = SubjectRadioConvert.INSTANCE.convertBoToRadio(option);
                        subjectRadio.setSubjectId(subjectInfoBo.getId());
                        subjectRadio.setIsDeleted(IsDeletedFlagEnum.UN_DELETED.getCode());
                        return subjectRadio;
                    }
            ).collect(Collectors.toList());

            subjectRadioService.batchInsert(subjectRadioList);
        } else {
            log.error("单选题插入失败，题目选项不能为空");
        }
    }

    @Override
    public SubjectOptionBo query(Long subjectId) {
        SubjectRadio subjectRadio = new SubjectRadio();
        subjectRadio.setSubjectId(subjectId);
        List<SubjectRadio> result = subjectRadioService.queryByCondition(subjectRadio);
        List<SubjectAnswerBo> subjectAnswerBOList = SubjectRadioConvert.INSTANCE.convertEntityToBoList(result);
        SubjectOptionBo subjectOptionBo = new SubjectOptionBo();
        subjectOptionBo.setOptionList(subjectAnswerBOList);
        return subjectOptionBo;
    }
}
